package com.bluexmicro.moduletester

import android.Manifest
import android.app.Activity
import android.os.Build
import android.view.WindowManager
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.google.accompanist.permissions.rememberPermissionState

@OptIn(ExperimentalMaterial3Api::class, ExperimentalPermissionsApi::class)
@Composable
fun TestPage() {

    val ctx = LocalContext.current
    val viewModel = viewModel<TestViewModel>()
    val testing = viewModel.testing.collectAsState()

    DisposableEffect(key1 = Unit) {
        val window = (ctx as? Activity)?.window
        window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        onDispose {
            window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val permissionState = rememberMultiplePermissionsState(
            permissions = listOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT
            )
        )
        LaunchedEffect(Unit) {
            permissionState.launchMultiplePermissionRequest()
        }
    } else {
        val permissionState =
            rememberPermissionState(permission = Manifest.permission.ACCESS_FINE_LOCATION)
        LaunchedEffect(Unit) {
            permissionState.launchPermissionRequest()
        }
    }

    var signal by remember {
        viewModel.signal
    }

    val currentDevice = viewModel.currentDevice.collectAsState()
    val successList = viewModel.successList.collectAsState()
    val failedList = viewModel.failedList.collectAsState()

    Scaffold(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .padding(it)
                .fillMaxSize()
        ) {

            Text(
                text = "信号强度：>${(signal - 127).toInt()}dbm",
                modifier = Modifier
                    .padding(horizontal = 32.dp)
                    .padding(top = 48.dp, bottom = 16.dp)
            )

            if (!testing.value) {
                Slider(
                    value = signal,
                    valueRange = 0f..126f, steps = 127,
                    onValueChange = { v ->
                        signal = v
                    },
                    colors = SliderDefaults.colors(),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 32.dp)
                        .padding(bottom = 16.dp)
                )
            }

            //开始结束、清空记录
            Button(
                onClick = { viewModel.toggle(ctx) },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .padding(horizontal = 32.dp)
            ) {
                val text = if (testing.value) "结束测试" else "开始测试"
                Text(text = text)
            }

            TextButton(
                onClick = { viewModel.clearRecords() },
                modifier = Modifier.align(Alignment.CenterHorizontally)
            ) {
                Text(text = "清空记录")
            }

            if (testing.value) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(32.dp)
                ) {

                    item {
                        Text(text = "当前设备", style = MaterialTheme.typography.titleLarge)
                        Spacer(modifier = Modifier.height(16.dp))
                        Card(Modifier.fillMaxWidth()) {
                            GridRow(entry = currentDevice.value)
                        }
                    }

                    item {
                        GridTitle(title = "成功列表")
                    }

                    itemsIndexed(successList.value) { index, entry ->
                        GridRow(index, entry)
                    }

                    item {
                        Spacer(modifier = Modifier.height(16.dp))
                        GridTitle(title = "失败列表")
                    }
                    itemsIndexed(failedList.value) { index, entry ->
                        GridRow(index, entry)
                    }

                }
            }
        }
    }

}

@Composable
private fun ResultIcon(res: Boolean?) {
    val iconRes = if (res != null) {
        if (res) R.drawable.ic_success else R.drawable.ic_failed
    } else {
        R.drawable.ic_idle
    }
    Icon(
        painter = painterResource(id = iconRes),
        contentDescription = null,
        tint = Color.Unspecified,
        modifier = Modifier.size(24.dp)
    )
}

@Composable
fun GridRow(index: Int? = null, entry: MyEntry?) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .defaultMinSize(minHeight = 64.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {

        if (index != null) {
            Text(text = "${index + 1}:")
        }

        Box(
            modifier = Modifier.fillMaxWidth(0.6f),
            contentAlignment = Alignment.Center
        ) {
            Text(text = entry?.address ?: "--")
        }

        Box(
            modifier = Modifier.weight(1f),
            contentAlignment = Alignment.Center
        ) {
            ResultIcon(res = entry?.tx)
        }

        Box(
            modifier = Modifier.weight(1f),
            contentAlignment = Alignment.Center
        ) {
            ResultIcon(res = entry?.rx)
        }
    }
}

@Composable
fun LazyItemScope.GridTitle(title: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .defaultMinSize(minHeight = 64.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {

        Text(
            text = title,
            Modifier.fillMaxWidth(0.6f),
            textAlign = TextAlign.Center
        )
        Text(
            text = "TX",
            Modifier.weight(1f),
            textAlign = TextAlign.Center
        )
        Text(
            text = "RX",
            Modifier.weight(1f),
            textAlign = TextAlign.Center
        )
    }
    Divider(thickness = Dp.Hairline)
}

